<template>
  <el-radio-group v-model="selectLabel" @change="dayChange">
    <el-radio-button label="sale_">销售量</el-radio-button>
    <el-radio-button label="_money">销售额</el-radio-button>
  </el-radio-group>
  <el-select v-model="selectDay" placeholder="Select" @change="dayChange">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.name"
      :value="item.value"
    />
  </el-select>
  <div id="mypie" style="width: 100%; height: 350px"></div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
//解决类型报错1：查看init类型
let myChart: echarts.ECharts;
const porps = defineProps<{ data: {}[] }>();
const state = reactive({
  selectLabel: "_money",
  selectDay: "today",
  options: [
    { name: "今天", value: "today" },
    { name: "昨天", value: "yesterday" },
    { name: "前3天", value: "three_days" },
    { name: "前7天", value: "seven_days" },
  ],
});
//解构
const { selectLabel, selectDay, options } = toRefs(state);

const dayChange = () => {
  initPie();
};
//封装获取的数据
const initPie = () => {
  let key = "";
  if (selectLabel.value === "_money") {
    key = selectDay.value + selectLabel.value;
  } else {
    key = selectLabel.value + selectDay.value;
  }
  //解决类型报错2：参数类型设置{[key:string]:string}
  const arr = porps.data.map((item: { [key: string]: string }) => ({
    value: item[key],
    name: item.name,
  }));
  //   console.log("porps-data:" + porps.data, "porps-arr:" + arr);
  // 初始化echarts实例
  if (!myChart) {
    myChart = echarts.init(document.getElementById("mypie") as HTMLElement);
  }
  const option = {
    tooltip: {
      trigger: "none",
    },
    legend: {
      top: "5%",
      left: "60%",
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["30%", "55%"],
        data: arr,
      },
    ],
  };
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
};
//异步请求会导致获取不到数据
watch(
  () => porps.data,
  () => {
    initPie();
  }
);
</script>

<style lang="less" scoped></style>
